package com.cn.reflection;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author he_ls
 * @since 2024/8/15 15:46
 **/
public class MyReflectionTest {
    public static void main(String[] args) {
        Class<?> c1 = null;
        try {
            c1 = Class.forName("com.cn.reflection.MyReflection");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        try {
            Constructor<?> con1 = c1.getDeclaredConstructor(Integer.class, String.class);
            // 解除私有限制
            con1.setAccessible(true);
            Object obj = con1.newInstance(11, "zs");
            assert obj instanceof MyReflection;
            MyReflection entity = (MyReflection) obj;
            System.out.println(entity);
            System.out.println("------注解获取-------");
            Annotation[] annotations = c1.getDeclaredAnnotations();
            for(Annotation anno : annotations) {
                System.out.println(anno);
            }


            System.out.println("------所有方法执行-------");
            Method[] methods = c1.getDeclaredMethods();
            for(Method method : methods) {
                System.out.println(method);
            }
            Method drawMethod = c1.getDeclaredMethod("draw", String.class);
            drawMethod.setAccessible(true);
            drawMethod.invoke(obj, "一条鱼");


            System.out.println("------成员变量-------");
            // 获取成员变量
//            Field[] fields = c1.getDeclaredFields();
            Field[] fields = c1.getFields();
            for(Field f : fields) {
                System.out.println(f);
            }

            Field age = c1.getDeclaredField("age");
            System.out.println(age);
//            age.setAccessible(true);
            age.set(obj, 22);
            System.out.println(obj);

            entity.eat();

            MyReflection myReflection = new MyReflection();
            myReflection.draw("年兽");

            new Thread(() -> {
                System.out.println("t1 start");

                System.out.println("t1 end");
            }).start();

            new Thread(() -> {
                System.out.println("t2 start");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("t2 end");
            }).start();

            System.out.println("main end");



        } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException |
                 NoSuchFieldException e) {
            throw new RuntimeException(e);
        }


    }
}
